import unittest
import json
import requests
from Finance_api import app
from Finance_api.api.register import RegisterAPI
from Finance_api.utils import common_assert
from parameterized import parameterized


def build_data():
    json_file = "./data/register.json"
    test_data = []
    with open(json_file, encoding="utf-8") as f:
        json_data = json.load(f)
        for case_data in json_data:
            register_data = case_data.get("register_data")

            # 获取短信验证码请求体
            phone = register_data.get("phone")
            verifycode = register_data.get("verifycode")
            type = case_data.get("type")

            status_code = case_data.get("status_code")
            status = case_data.get("status")
            description = case_data.get("description")

            test_data.append((register_data, phone, verifycode, type, status_code, status, description))
    return test_data


class TestRegister(unittest.TestCase):
    def setUp(self):
        self.register_api = RegisterAPI()
        self.session = requests.Session()

    def tearDown(self):
        if self.session:
            self.session.close()

    @parameterized.expand(build_data())
    def test_register(self, register_data, phone, verifycode, type, status_code, status, description):
        # 获取图片验证码
        response = self.register_api.get_verify_code(self.session)
        self.assertEqual(status_code, response.status_code)

        jsessionid = response.headers.get("Set-Cookie").split("; ")[0]
        # 提取Cookie信息
        app.Cookie = jsessionid
        app.headers_data["Cookie"] = app.Cookie

        # 获取手机验证码
        response = self.register_api.get_phone_code(self.session, phone=phone, verifycode=verifycode, type=type)
        common_assert(self, response, status_code, status, "短信发送成功")
        print(response.json())

        # 注册
        response = self.register_api.register(self.session, register_data=register_data)
        common_assert(self, response, status_code, status, description)
        print(response.json())
